package com.pinyoumei.app.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.AilipyInitBean;
import com.pinyoumei.app.bean.BaseBean;
import com.pinyoumei.app.bean.CodeBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.AppManager;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.StatusBarUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.event.BackBuyEvent;
import com.pinyoumei.app.utils.event.GroupEvent;
import com.pinyoumei.app.utils.event.RecharEvent;
import com.pinyoumei.app.utils.event.ReshEvent;
import com.pinyoumei.app.view.LoadingDailog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2021-08-16.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-16        Administrator             新增Person类
 * 2021-08-16        Administrator             增加sex属性
 * 支付宝账号
 */
public class AliPayPasswordActivity  extends AppCompatActivity implements View.OnClickListener {

    private Button bt_register;
    private EditText et_code;

    private EditText et_password2;
    private TextView tvSendCode;
    private TextView tv_phone;
    private TextView tv_name;
    private String phone = "";
    private String name = "";
    protected AppManager appManager = AppManager.getInstance();
    private Gson gson;
    private LoadingDailog loadingDailog;
    private TimeCount timeCount;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtils.setRootViewFitsSystemWindows(this,true);
        //设置状态栏透明
        StatusBarUtils.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtils.setStatusBarDarkTheme(this, true)){
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtils.setStatusBarColor(this,0x55000000);
        }
        // 添加activity 到栈
        appManager.addActivity(this);

        gson = new Gson();
        LoadingDailog.Builder builder = new LoadingDailog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();

        setContentView(R.layout.activity_ali_password);

        InitWidget();
        InitData();
    }



    private void InitWidget() {
        RelativeLayout relative_finish = findViewById(R.id.relative_finish);
        relative_finish.setOnClickListener(this);

        tv_name = findViewById(R.id.tv_name);
        tv_phone = findViewById(R.id.tv_phone);
        tvSendCode = findViewById(R.id.tv_send_code);
        tvSendCode.setOnClickListener(this);

        et_code = findViewById(R.id.et_code);

        et_password2 = findViewById(R.id.et_password2);


       TextChange textChange = new TextChange();
        et_code.addTextChangedListener(textChange);

        et_password2.addTextChangedListener(textChange);

        bt_register = findViewById(R.id.bt_register);
        bt_register.setOnClickListener(this);
    }

    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(AliPayPasswordActivity.this));

        OkGo.<String>post(Constants.SETTING_ZFB_INIT)
                .params("user_id", SPUtils.getAppUserId(AliPayPasswordActivity.this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {



                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        AilipyInitBean ailipyInitBean = gson.fromJson(response.body(), AilipyInitBean.class);

                        if (ailipyInitBean.getCode() >= 0) {
                            phone = ailipyInitBean.getResult().getUser_phone();
                            tv_phone.setText("账户手机号：" + phone);
                            name = ailipyInitBean.getResult().getUser_real_name();
                            tv_name.setText("支付宝姓名：" + name);
                        } else {
                            ToastUtils.showShort(ailipyInitBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }
    //EditText的监听器
    class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if (et_code.length() > 0 &&
                    et_password2.length() > 0) {
                bt_register.setBackground(ContextCompat.getDrawable(AliPayPasswordActivity.this, R.drawable.shanpe_green_5dp));
                bt_register.setEnabled(true);
                bt_register.setClickable(true);
            } else {
                bt_register.setBackground(ContextCompat.getDrawable(AliPayPasswordActivity.this, R.drawable.shanpe_gray_green_5dp));

                bt_register.setEnabled(false);
                bt_register.setClickable(false);
            }
        }
    }

    //计时器类
    class TimeCount extends CountDownTimer {
        //构造方法
        public TimeCount(long millisInFuture, long countDownInterval) {//第一个参数是计时器的总时间是60s 第二个参数是间隔是1s
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvSendCode.setText("重新获取(" + millisUntilFinished / 1000 + "s)");
            tvSendCode.setTextColor(Color.parseColor("#438FF5"));
            tvSendCode.setClickable(false);
        }

        @Override
        public void onFinish() {
            tvSendCode.setText("获取验证码");
            tvSendCode.setTextColor(Color.parseColor("#438FF5"));
            tvSendCode.setClickable(true);
        }
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.relative_finish:
                finish();
                break;
            case R.id.tv_send_code:
                if (!TextUtils.isEmpty(phone)){
                    SendCode(phone,5);

                }

                break;
            case R.id.bt_register:
                String code = et_code.getText().toString().trim();
                String pwd = et_password2.getText().toString().trim();
                if (TextUtils.isEmpty(code)){
                    ToastUtils.showShort("请输入验证码");
                }else if (TextUtils.isEmpty(pwd)){
                    ToastUtils.showShort("请输入支付宝账号");
                }else{
                    SubmitData(code,pwd);
                }

                break;
            default:
                break;
        }
    }

    private void SendCode(String phone,int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", phone);
        map.put("type", type);

        OkGo.<String>post(Constants.SendMSG)
                .params("user_phone", phone)
                .params("type", type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        CodeBean codeBean = gson.fromJson(response.body(), CodeBean.class);

                        if (codeBean.getCode() >= 0) {
                            if (timeCount == null) {
                                timeCount = new TimeCount(60 * 1000, 1000);//5s的一个定时器 间隔是1s
                                timeCount.start();
                            }


                            Toast.makeText(AliPayPasswordActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(AliPayPasswordActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }
    private void SubmitData(String verify_code,String user_alipay_account) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(AliPayPasswordActivity.this));
        map.put("verify_code", verify_code);
        map.put("user_alipay_account", user_alipay_account);

        OkGo.<String>post(Constants.SETTING_ZFB_SUBMIT)
                .params("user_id", SPUtils.getAppUserId(AliPayPasswordActivity.this))
                .params("verify_code", verify_code)
                .params("user_alipay_account", user_alipay_account)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        BaseBean settingUserBean = gson.fromJson(response.body(), BaseBean.class);

                        if (settingUserBean.getCode() >= 0) {
                            EventBusUtils.post(new ReshEvent("1"));
                            EventBusUtils.post(new RecharEvent("1"));
                            EventBusUtils.post(new GroupEvent("1"));
                            EventBusUtils.post(new BackBuyEvent("1"));
                            ToastUtils.showShort(settingUserBean.getMsg());
                            finish();

                        } else {
                            ToastUtils.showShort(settingUserBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }
}
